<!--
 * @Author: zhang ke
 * @Date: 2025-06-24 16:01:05
 * @LastEditors: your name
 * @LastEditTime: 2025-06-28 11:22:46
 * @Description: 
 * @FilePath: \vue3-admin\src\views\product\attr\index.vue
-->
<template>
  <div>
    <!-- 分类 -->
    <Category :scene="scene"></Category>
    <!-- table -->
    <el-card style="margin: 10px 0;">
      <div v-if="scene == 0">
        <el-button @click="changeAttr" type="primary" style="margin-bottom: 20px;"
          :disabled="useCategory.c3Id ? false : true">
          <el-icon>
            <Plus />
          </el-icon>
          属性管理
        </el-button>
        <el-table :data="tableData" border>
          <el-table-column prop="id" label="序号" width="100" align="center" />
          <el-table-column prop="attrName" label="属性名称" width="200" />
          <el-table-column prop="name1" label="属性值名称">
            <template #default="scope">
              <el-tag v-for="(item, index) in scope.row.attrValueList" style="margin: 5px;">
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" width="230">
            <template #default="scope">
              <el-button size="small" type="warning" icon="Edit" @click="changeAttr('edit',scope.row)">
              </el-button>
              <el-popconfirm :title="`确定删除属性名称为${scope.row.attrName}嘛？`" @confirm="handleDelete(scope.row.id)" width="270px">
                <template #reference>
                  <el-button size="small" type="danger" icon="Delete">
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="scene == 1">
        <el-form>
          <el-form-item label="属性名称">
            <el-input placeholder="请输入属性的名字" v-model="attrParams.attrName" style="width: 240px;" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addAttr" :disabled="attrParams.attrName ? false :true">
              <el-icon>
                <Plus />
              </el-icon>
              添加属性值
            </el-button>
            <el-button @click="cancel">取消</el-button>
          </el-form-item>
          <el-form-item>
            <el-table border :data="attrParams.attrValueList">
              <el-table-column type="index" label="序号" width="100" align="center" />
              <el-table-column prop="valueName" label="属性值">
                <template #default="scope">
                  <input :ref="(vc)=>inputArr[scope.$index]=vc" v-if="scope.row.flag" v-model="scope.row.valueName" @blur="blurValueName(scope.row,1,scope.$index)" placeholder="请输入属性的名字" />
                  <div v-else @click="blurValueName(scope.row,0,scope.$index)">{{ scope.row.valueName }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="address" label="操作">
                <template #default="scope">
                  <el-button size="small" type="danger" icon="Delete" @click="delValueName(scope.$index)">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :disabled="attrParams.attrValueList.length > 0 ? false :true" @click="save">
              保存
            </el-button>
            <el-button @click="cancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {ref,watch,reactive,nextTick,onBeforeUnmount} from 'vue'
import Category from '@/components/Category/index.vue'
import useCategoryStore from '@/store/modules/category'
import type {Attr,AttrResponseData,AttrValue} from '@/api/product/attr/type'
import {reqAttr,reqAddOrUpdateAttr,reqRemoveAttr} from '@/api/product/attr/index'
import { ElMessage } from 'element-plus'
const useCategory = useCategoryStore()
const tableData = ref<Attr[]>([])
const scene = ref<number>(0)
const inputArr = ref<any>([])
let attrParams = reactive<Attr>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3,
})
//监听三级id去调用获取数据接口
watch(()=>useCategory.c3Id,()=>{
  tableData.value = []
  
  if(!useCategory.c3Id) return //如果三级id不存在就不继续执行
  getAttrData()
})
//table接口
const getAttrData = async()=>{
   let res:AttrResponseData = await reqAttr(useCategory.c1Id,useCategory.c2Id,useCategory.c3Id)
   if(res.code == 200){
      tableData.value = res.data
   }
}
//点击新增和编辑
const changeAttr = (type:string,row:AttrValue)=>{
  scene.value = 1
  //获取三级分类id
  attrParams.categoryId = useCategory.c3Id
  //每次打开前都清空数据
  Object.assign(attrParams, {
    attrName: '',
    attrValueList: [],
    categoryId: '',
    categoryLevel: 3,
  })
  if(type == 'edit'){
    Object.assign(attrParams,JSON.parse(JSON.stringify(row)))
  }
  
}
const cancel = ()=>{
  scene.value = 0
}
// 添加属性值
const addAttr = ()=>{
// valueName
  attrParams.attrValueList.push({
    valueName: '',
    flag:true,
  })
  //让输入框自动获取焦点
  nextTick(()=>{
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
//保存
const save = async()=>{
  let res = await reqAddOrUpdateAttr(attrParams)
  if(res.code == 200){
    //返回table列表并刷新数据
    scene.value = 0
    getAttrData()
    ElMessage({
      type:'success',
      message:attrParams.id ? '修改成功' : '新增成功'
    })
  }else{
      ElMessage({
      type:'error',
      message:attrParams.id ? '修改失败' : '新增失败'
    })
  }
}
//删除
const handleDelete = async(id:number)=>{
  let res = await reqRemoveAttr(id)
  if(res.code == 200){
     getAttrData()
    ElMessage({
      type:'success',
      message:'删除成功'
    })
  }else{
    ElMessage({
      type:'error',
      message:'删除失败'
    })
  }

}

//输入框失去焦点| 点击div时
const blurValueName = (row:AttrValue,type:number,index:number)=>{

  //当input输入框为空时
  if(row.valueName.trim()=== ''){
    attrParams.attrValueList.splice(index,1)
    ElMessage({
      type:'error',
      message:'属性值不能为空'
    })
    return
  }
  // 当input内属性值相同时
  let repeat = attrParams.attrValueList.find((item)=>{
    if(item !== row){
      return item.valueName === row.valueName
    }
  })
  if(repeat){
    attrParams.attrValueList.splice(index,1)
     ElMessage({
      type:'error',
      message:'属性值不能重复'
    })
    return
  }
  // 输入框失去焦点
  if(type == 1){
    row.flag = false

  }
  // 点击div时
  if(type == 0){
    row.flag = true
    //让输入框自动获取焦点
    nextTick(()=>{
      inputArr.value[index].focus()
    })
  }
  
}
//删除属性的事件
const delValueName = (index:number)=>{
   attrParams.attrValueList.splice(index,1)
}
// 清除仓库中的值
onBeforeUnmount(()=>{
  useCategory.$reset()
})
</script>

<style scoped>
</style>
